import numpy as np
from matplotlib import pyplot as plt

raw_data_X = [[3.393533211, 2.331273381],
              [3.110073483, 1.781539638],
              [1.343808831, 3.368360954],
              [3.582294042, 4.679179110],
              [2.280362439, 2.866990263],
              [7.423436942, 4.696522875],
              [5.745051997, 3.533989803],
              [9.172168622, 2.511101045],
              [7.792783481, 3.424088941],
              [7.939820817, 0.791637231]
             ]
raw_data_y = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

x_train = np.array(raw_data_X)
y_train = np.array(raw_data_y)


def show_plot(x_train, y_train,predict):
    plt.scatter(x_train[y_train == 1, 0], x_train[y_train == 1, 1], color='g')
    plt.scatter(x_train[y_train == 0, 0], x_train[y_train == 0, 1], color='r')
    plt.scatter(predict[0],predict[1], color='b')
    plt.show()


from math import sqrt
from collections import Counter


def computer_distances(x_in, k):
    distances = []
    for x in x_train:
        d = sqrt(np.sum(x - x_in) ** 2)
        distances.append(d)
    index_list = np.argsort(distances)
    top_k = [y_train[i] for i in index_list[:k]]
    # t统计数量
    cpunt_re = Counter(top_k)

    label = cpunt_re.most_common(1)[0][0]
    return label


if __name__ == '__main__':
    predict=np.array([1, 3])
    show_plot(x_train, y_train,predict)
    label = computer_distances(predict, 1)
    print(f'预测标签是{label}')
